package com.wflow.workflow.service.impl;

import com.wflow.workflow.service.BusinessDataStorageService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 业务数据存储服务
 * @author : willian fu
 * @date : 2023/10/27
 */
public class DefaultBusinessDataStorageServiceImpl implements BusinessDataStorageService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Override
    public Map<String, Object> getInstanceFormData(String instanceId) {
        return historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(instanceId)
                .variableNameLike("field%")
                .list().stream().collect(Collectors.toMap(
                        HistoricVariableInstance::getVariableName,
                        HistoricVariableInstance::getValue
                ));
    }

    @Override
    public Map<String, Object> getInstanceFormFieldsById(String instanceId, String... fieldIds) {
        return null;
    }

    @Override
    public void saveFormDataByInstance(String formId, String defId, String instanceId, Map<String, Object> formData) {
        runtimeService.setVariables(instanceId, formData);
    }

    @Override
    public void updateFormDataByInstance(String formId, String defId, String instanceId, Map<String, Object> formData) {
        runtimeService.setVariables(instanceId, formData);
    }
}
